<template>
	<view>


		<!-- 审批流程显示 -->

		<u-popup id="popup-box" :show="showFormApprove" mode="center" bgColor="transparent" :closeOnClickOverlay="false"
			@close="closeApprovePopup">
			<!-- <template> -->

			<view class="f-dc" style="width: 90vw;background-color: #fff;border-radius: 12px;overflow: hidden;">
				<u-navbar class="navbar" leftText="审批单据" leftIconColor="#fff" leftIcon=" "
					@rightClick="closeApprovePopup" :fixed="false" :autoBack="false" :safeAreaInsetTop="false"
					rightIcon="close" rightIconColor="#fff">
				</u-navbar>

				<view class="TabsBox">
					<m-scroll-tag @tabChange="changeTab" :tagsList="ApproveTabList" bgColor="#52b583">
					</m-scroll-tag>
				</view>

				<scroll-view v-show="currentIndex==0" class="scroll-Y" style="width: 100%;"
					:style="{height:scollViewHeight+'px'}" scroll-y="true">
					<mApprovalShowByDeal style="zoom: 0.8;" :option="BaseScreenParm" @openPreview="openPreview">
					</mApprovalShowByDeal>
				</scroll-view>


				<scroll-view v-show="currentIndex==1" class="scroll-Y" style="width: 100%;"
					:style="{height:scollViewHeight+'px'}" scroll-y="true">
					<view class="scrollBottomBox1" style="height: 100%;">

						<uni-section title="文件上传" type="line" style="margin-top: 10px;">
							<view style="padding: 0 10px;">

								<cl-upload v-model="uploadFile_list"
									:listStyle="{columns: 4,padding:'6px',columnGap:'10px',rowGap:'10px'}"
									useBeforeDelete @beforeDelete="beforeDelete" cloudType="other"
									:action="uploadFile_action" @onSuccess="onSuccess"></cl-upload>

							</view>
						</uni-section>


						<uni-section title="输入审批建议" type="line" style="padding: 0 10px;">
							<!-- <uni-easyinput type="textarea" :style="{height:'60rpx'}" v-model="ApprovalContent"
								placeholder="请输入输入审批建议"></uni-easyinput> -->
							<u--textarea v-model="ApprovalContent" height="50" placeholder="请输入输入审批建议"></u--textarea>
						</uni-section>


						<!-- <view class="x-bc" style="height: 70px;"> -->

					</view>
				</scroll-view>



				<view class="x-bc" style="padding: 10px;">
					<button @click="returnApproval" class="content_bottom_primary_plainBtn CommonBtnSize"
						:disabled="!enabledSubmitBtn" style="margin-right: 8px;">转交</button>
					<button @click="dealApproval(2)" class="content_bottom_primary_plainBtn CommonBtnSize"
						:disabled="!enabledSubmitBtn" style="margin-right: 8px;">拒绝</button>
					<button @click="dealApproval(1)" class="content_bottom_primary_Btn CommonBtnSize"
						:disabled="!enabledSubmitBtn">确认通过</button>
				</view>
			</view>
			<!-- </template> -->



			<u-popup :show="popup_approve" mode="center" :closeOnClickOverlay="false" :zIndex="9999999" :round="4"
				@close="closepersonApprovePopup">
				<view class="popup-content">

					<view class="popup-content_close x-c" @click="closepersonApprovePopup">
						<uni-icons type="closeempty" color="#999" size="14"></uni-icons>
					</view>

					<view class="x-f title">
						<text>人员转交</text>
					</view>

					<view class="popup-content_desc">
						<text>是否确认转交给{{popup_approve_form.UserName}}</text>
					</view>



					<view class="btnBox x-ac">
						<u-button type="primary" text="确认" @click="submitApprovePopup"></u-button>

						<u-button text="取消" @click="closepersonApprovePopup"></u-button>
					</view>

				</view>
			</u-popup>



			<!-- 图片预览s -->
			<m-previewImage ref="previewImage" mode="widthFix" @onLongpress="onLongpress"
				:urls="imagesPreview"></m-previewImage>
		</u-popup>

	</view>
</template>

<script>
	import mApprovalShowByDeal from '@/uni_modules/mc-ui/components/m-node-warp/compontent/m-approvalShowByDeal/m-approvalShowByDeal.vue';

	export default {
		name: "mFormApprovePopup",
		components: {
			mApprovalShowByDeal
		},
		data() {
			return {
				enabledSubmitBtn: true, // 控制按钮点击
				currentIndex: 0,
				ApproveTabList: [{
						name: '审批流程',
						value: 0
					},
					{
						name: '附件/备注',
						value: 1
					}
				],

				imagesPreview: [],
				uploadFile_action: '',
				uploadFileKey: '', // 文件上传字段
				uploadFile_list: [],
				ApprovalContent: '',
				scollViewHeight: 200,
				// #ifdef APP-PLUS
				eventChannel: null,
				// #endif
				BaseScreenParm: {},
				popup_approve: false, // 是否转交弹层
				popup_approve_form: {},
			};
		},
		created() {
			// #ifdef APP-PLUS
			this.eventChannel = this.getOpenerEventChannel();
			// #endif
			this.uploadFile_action = this.Request.IPAgreement() + this.Request.serverIP() + '/FileData/UploadSignleFile';

			this.BaseScreenParm = uni.$m.utils.deepClone(this.$store.state.BaseScreenParm);


		},
		computed: {

			showFormApprove() {
				return this.$store.state.st_comPageConfig.showFormApprove;
			},
		},
		watch: {
			showFormApprove: {
				handler(nVal) {
					if (nVal) {
						this.getViewHeight();
					}
				},
				deep: true,
				immediate: true
			}
		},
		mounted() {
			let that = this;
			uni.$on('mFormApprove_Choice', function(ret) {
				if (ret.type == '转交人员') {
					that.popup_approve_form = uni.$m.utils.deepClone(ret.data);
					that.popup_approve = true;
				}
			})
		},
		onUnload() {
			this.eventChannel.emit('cancel');
			uni.$off('mFormApprove_Choice');
		},
		methods: {
			changeTab(item) {
				this.currentIndex = item.Index;
			},
			submitApprovePopup() { // 确认转交
				let that = this;

				if (!this.enabledSubmitBtn) {
					return;
				}
				this.enabledSubmitBtn = false;
				let obj = {
					ApprovalSort: this.BaseScreenParm.ApprovalSort,
					KeyID: this.BaseScreenParm.keyValue,
					TableName: this.BaseScreenParm.globalData['physicalTableName'],
					returnUserID: this.popup_approve_form['UserID'],
					ApprovalID: this.BaseScreenParm.ApprovalID,
				}
				this.Request.request('Ck_ReturnApproval', obj, function(ret) {
					if (ret.status == 200) {
						if (ret.data.ds[0]['STATUS'] == 0) {
							uni.$m.utils.msg('转交成功');

							that.closepersonApprovePopup();
							that.closeApprovePopup('confirm');
						} else {
							uni.$m.utils.msg(ret.data.ds[0]['msg']);
							that.closepersonApprovePopup();
						}

					} else {
						uni.$m.utils.msg('请求失败，请重试');
						that.closepersonApprovePopup();
					}
				})


			},
			closepersonApprovePopup() { // 关闭转交
				this.popup_approve = false;
			},
			returnApproval() { // 转交


				this.openBaseScreen('转交人员', 'radio')
			},
			dealApproval(approveType) { // 拒绝 、确认通过
				let that = this;

				if (!this.enabledSubmitBtn) {
					return;
				}
				this.enabledSubmitBtn = false;

				uni.$m.utils.showLoading();
				let approveImgs = this.uploadFile_list.map(item => {
					return item.path;
				});
				let obj = {
					ApprovalSort: this.BaseScreenParm.ApprovalSort, // 审批顺序
					Approve: approveType, // 通过/未通过
					KeyID: this.BaseScreenParm.keyValue,
					TableName: this.BaseScreenParm.globalData['physicalTableName'], // 物理表名
					Imgs: approveImgs.join(','), //
					ApprovalID: this.BaseScreenParm.ApprovalID, // 审批流ID

					ApprovalContent: this.ApprovalContent,
				};
				this.Request.request('Ck_ApprovalForm', obj, function(ret) {
					uni.$m.utils.hideLoading();
					if (ret.status == 200) {
						if (ret.data.ds[0]['STATUS'] == 0) {
							//审批完成的脚本

							let workConfig = JSON.parse(that.BaseScreenParm.globalData['approvalConfig'])
								.workConfig;
							if (ret.data.ds[0].isFinished == '1') {


								if (workConfig[2].script) {

									that.closeApprovePopup('doneConfirm', '2');

								} else {
									uni.$m.utils.msg('审批完成');

									that.closeApprovePopup('confirm');
								}


							} else {
								if (workConfig[1].script) {
									// let work = workConfig[2].script;
									that.closeApprovePopup('doneConfirm', '1');

								} else {
									uni.$m.utils.msg('审批完成');

									that.closeApprovePopup('confirm');
								}

							}

						} else {
							uni.$m.utils.msg(ret.data.ds[0]['msg'])
						}
					} else {
						uni.$m.utils.msg('请求失败，请重试')
					}
				}, function(err) {

					uni.$m.utils.hideLoading();
				})


			},
			openBaseScreen(str, type) { // 前往筛选页
				let that = this;

				if (type == 'radio') {
					let obj = null;
					let url = '/commonPage/Tool/baseScreen';

					if (str == '转交人员') {
						let userID = this.$store.state.UserInfo.UserID;
						obj = {
							allowClear: false,
							cmd: 'getCkUserList',
							type: str,
							ListeningName: 'mFormApprove_Choice',
							// multiple: false,
							serverSearch: {
								isPaging: false, //是否分页
								searchKey: '', //搜索关键词，应包含在param中
								showText: 'UserName', //查询结果显示的字段
								// pageIndexStr: 'pageIndex', //分页页码字段，应包含在param中
								// subText: [{
								// 	label: '描述',
								// 	labelKey: 'desc'
								// }],
								disabled: { // 需要禁用的数据
									data: [userID],
									key: 'UserID'
								},
							},
							param: {}
						}
					}

					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: obj
					})

					uni.navigateTo({
						url: url,
					})

				}

			},

			getViewHeight() { // 获取高度
				let that = this;
				let res = uni.getSystemInfoSync();

				let safeArea = res.safeAreaInsets; // 安全区域嵌入 top - bottom
				let safe = safeArea.top + safeArea.bottom
				let windowHeight = (res.windowHeight - safe) * 0.6; // 总高
				let navHeight = 0;
				setTimeout(() => {
					uni.createSelectorQuery().select('.navbar').boundingClientRect(rect => {
						navHeight = rect.height;
						that.scollViewHeight = windowHeight - navHeight;
						// uni.createSelectorQuery().select('.scrollBottomBox').boundingClientRect(ret => {
						// 	let nextData = windowHeight - navHeight - ret.height;

						// 	that.scollViewHeight = nextData;
						// }).exec();
					}).exec();
				}, 300);
			},

			closeApprovePopup(type = 'cancel', data = null) { // 关闭弹层
				this.hide(type, data);

			},
			// 弹窗关闭后需要重置popupConfig数据
			hide(type, data = null) {
				let _this = this;
				// 关闭弹窗
				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'st_comPageConfig.showFormApprove',
					data: true
				})
				setTimeout(() => {
					_this.$store.commit('ChangeAndSetStateData', {
						Name1: 'st_comPageConfig.showFormApprove',
						data: false
					})

					// uni.navigateBack();

					uni.navigateBack({
						delta: 1,
						success() {
							_this.eventChannel.emit(type, data);
						}
					})
				}, 100) // 这里时间就是弹窗显示隐藏动画时间
			},


			onLongpress(e) { //长按事件
				let imagePath = e;

				uni.showActionSheet({
					itemList: ['保存到手机'],
					success: function(res) {

						uni.saveImageToPhotosAlbum({
							filePath: imagePath, // 图片文件路径
							success: function() {
								uni.showToast({
									title: '已保存到相册',
									icon: 'success'
								});
							},
							fail: function(error) {
								uni.showToast({
									title: '图片保存失败，请检查权限',
									icon: 'none'
								});
							}
						});

					}
				});
			},
			openPreview(data, index) { // 预览图片
				let that = this;
				this.imagesPreview = data || [];
				if (data.length) {
					this.$refs.previewImage.open(data[index]);
				}
			},
			beforeDelete({
				fileToDelete,
				uploadKey
			}, index, next) {
				let that = this;
				console.log(that.uploadFile_list);
				// console.log(that.formData[that.uploadFileKey]);
				// let arr = that.formData[that.uploadFileKey].split(',')
				uni.showModal({
					title: '提示信息',
					content: '确定要删除这个文件嘛？',
					success: res => {
						if (res.confirm) {
							that.uploadFile_list.splice(index, 1);

							// that.formData[that.uploadFileKey] = arr.join(',')

							// 模拟服务器接口
							setTimeout(() => {
								next();
							}, 300);
						}
					}
				});
			},
			onSuccess(data) {
				console.log(data);
				let path = this.Request.IPAgreement() + this.Request.serverIP() + data.data;
				console.log(path);
				this.uploadFile_list.push({
					path: path
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background: transparent;
		height: 100vh;
	}

	// 顶部tab栏
	.TabsBox {
		padding: 10px 8px;
		background-color: #fff;
		border-bottom: 2px solid #eee;

		.u-tabs__wrapper__nav__item__text {
			padding: 4px 10px !important;
		}
	}


	// 转交
	.popup-content {
		position: relative;
		display: flex;
		flex-direction: column;
		background-color: #fff;
		width: 86vw;
		max-width: 500px;
		padding: 40rpx 20px 30rpx;
		font-size: 12px;
		border-radius: 4px !important;
		overflow: hidden;

		&_close {
			position: absolute;
			top: 0;
			right: 0;
			width: 28px;
			height: 28px;
			font-weight: 600;
		}

		.title {
			font-size: 16px;
			font-weight: 600;
			text-align: center;
		}

		&_desc {
			margin: 24rpx 0;
			text-align: center;
			color: #999;
		}

		.check {
			zoom: .9;
			font-size: 13px;
			color: #999;
		}

		.btnBox {
			margin-top: 20px;

			.u-button {
				width: 44% !important;
			}
		}
	}
</style>